const log = console.log.bind(console)

class Stroage {
  constructor() {
    // console.log('debug this._load()', this._load())
    this.data_id = this._load().data_id || -1
    this.data = this._load().data || []
    this._save(this.data)
    this._singleton = null
  }

  static getSingleton() {
    if(!window._singleton) {
      this._singleton = new this()
    }
    return this._singleton;
  }

  _save(data) {
    let obj = {}
    obj.data = data
    obj.data_id = this._nextId()
    const s = JSON.stringify(obj)
    localStorage.setItem('todo', s)
    // console.log('debug save success')
  }

  _load() {
    const s = localStorage.getItem('todo') || '{}'
    const obj = JSON.parse(s)
    return obj
  }


  _nextId() {
    this.data_id++
    return this.data_id
  }

  get(name) {
    let stroage = this._load()
    return stroage.data.find(n => {
      return n.name === name
    })
  }

  set(name, data) {
    let stroage = this._load().data
    let n = {
      name: name,
      id: this._nextId(),
    }
    let obj = Object.assign(n, data)
    stroage.push(obj)
    this._save(stroage)
    return this._load()
  }

  remove(id) {
    let d = this.all().filter(n => n.id !== id)
    this._save(d)
  }

  complete(id) {
    this.all().forEach(n => n.id === id ? n.completed = !n.completed : null)
  }

  all() {
    return this._load().data
  }
}


export default Stroage.getSingleton()

